import axios from 'axios'
import router from '@/router'
import { state, actions } from '@/store/app'
import type { AxiosRequestConfig } from 'axios'

const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 10 * 1000,
    // withCredentials: true,
    headers: {
        'x-source': 'coinpay',
        env: import.meta.env.MODE === 'production' ? 'prod' : 'test',
        language: 'zh-cn',
        authorization: state.token
    }
})

const API_ERROR: { [key: number]: string } = {
    400: 'Request Error (400)',
    404: 'Request Error (404)',
    408: 'Request Timed Out (408)',
    500: 'Server Error (500)',
    501: 'Service Not Implemented (501)',
    502: 'Network Error (502)',
    503: 'Service Unavailable (503)',
    504: 'Network Timeout (504)',
    505: 'HTTP version is not supported (505)'
}

const whiteRoutes = ['/', '/login', '/register', '/forget']

export const io = async <T>(config: AxiosRequestConfig): Promise<[undefined, T] | [unknown, undefined]> => {
    try {
        config.headers = { ...config.headers, authorization: state.token }
        const { data, status, statusText } = await instance.request<Api.ApiCommon.Response<T>>(config)
        if (status === 200 || status === 204) {
            const { code, data: result, msg } = data

            if (code === 0) {
                return [undefined, result]
            }
            if (code === '1000000') {
                if (!whiteRoutes.includes(router.currentRoute.value.path)) {
                    if (state.token) {
                        window.$message.error('token 过期，请重新登录')
                    }
                    router.push('/login')
                }

                actions.clear()
                return [data, undefined]
            }

            if (code === '1000001') {
                window.$message.error('参数错误')
                return [data, undefined]
            }

            if (code === '2000001') {
                window.$message.error('无效的请求源')
                return [data, undefined]
            }

            if (code === '2000002') {
                window.$message.error('业务异常，请稍后再试')
                return [data, undefined]
            }

            window.$message.error(msg)
            return [data, undefined]
        }

        window.$message.error(statusText)
        return [data, undefined]
    } catch (err) {
        let msg: string

        if (axios.isAxiosError(err) && err.response) {
            const { status } = err.response
            msg = API_ERROR[status] || `Connection Error'(${status})`
        } else {
            msg = 'Connection Failure'
        }

        window.$message.error(msg)
        return [err, undefined]
    }
}
